package com.yulongtian.interviewWorks.day20220823;

import java.util.Stack;

/**
 * @author YulongTian
 * @date 2022/8/23 - 16:14
 */
public class InterviewsWork05 {

    public static void main(String[] args) {
        System.out.println(oneEditAway("teacher", "bleacher"));
    }

    public static boolean oneEditAway(String first, String second) {
        int firstLen = first.length();
        int secondLen = second.length();
        if (Math.abs(firstLen - secondLen) > 1) {
            return false;
        }
        if (firstLen + secondLen <= 2) {
            return true;
        }

        Stack<Character> stack01 = new Stack<>();
        Stack<Character> stack02 = new Stack<>();

        for (int i = 0; i < firstLen; i++) {
            stack01.push(first.charAt(i));
        }
        for (int i = 0; i < secondLen; i++) {
            stack02.push(second.charAt(i));
        }

        if (firstLen == secondLen) {
            int res = 0;


            for (int i = 0; i < firstLen; i++) {
                if (stack01.pop() != stack02.pop()) {
                    res++;
                }
            }
            if (res > 1) {
                return false;
            }
        } else {
            int res = 0;
            int maxLen = firstLen > secondLen ? firstLen : secondLen;
            for (int i = 0; i < maxLen; i++) {
                if (!stack01.empty() && !stack02.empty()) {

                    Character pop1 = stack01.pop();
                    Character pop2 = stack02.pop();
                    if (pop1 != pop2) {
                        res++;
                        if (res > 1) {
                            return false;
                        }
                        if (firstLen > secondLen) {
                            stack02.push(pop2);
                        } else {
                            stack01.push(pop1);
                        }

                    }
                }
            }
        }
        return true;
    }


}
